package com.example.anni.zhuzhoujia.xiaowan;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.lhh.ptrrv.library.PullToRefreshRecyclerView;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Anni on 2016/7/2.
 */
public class ReadHistoryActivity extends AppCompatActivity {
    private PullToRefreshRecyclerView mPtrrv;
    private List<Map<String, String>> mDatas;
    private MyReadHistoryAdapter mAdapter;
    private JSONArray arr;
    private static final int DEFAULT_ITEM_SIZE = 10;
    private static final int ITEM_SIZE_OFFSET = 5;

    private static final int MSG_CODE_REFRESH = 0;
    private static final int MSG_CODE_LOADMORE = 1;

    private static final int TIME = 1000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_history_activity);
        initToolbar();
        initData();
        initView();
    }

    private void initToolbar() {
        TextView tvNameTitle;
        tvNameTitle = (TextView) findViewById(R.id.tv_name_title);
        tvNameTitle.setText("浏览历史");
    }

    private void initView() {
        mPtrrv = (PullToRefreshRecyclerView) findViewById(R.id.prrv_read_history);
        mPtrrv.setSwipeEnable(true);
        //加载条
        DemoLoadMoreView loadMoreView = new DemoLoadMoreView(this, mPtrrv.getRecyclerView());
        loadMoreView.setLoadmoreString(getString(R.string.loadmore));
        loadMoreView.setLoadMorePadding(100);
        //线性管理器
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mPtrrv.setLayoutManager(layoutManager);
        mPtrrv.setPagingableListener(new PullToRefreshRecyclerView.PagingableListener() {
            @Override
            public void onLoadMoreItems() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_LOADMORE, TIME);
            }
        });
        mPtrrv.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_REFRESH, TIME);
            }
        });
        //设置下划线
        mPtrrv.getRecyclerView().addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        //设置动画
        mPtrrv.getRecyclerView().setItemAnimator(new DefaultItemAnimator());
        mPtrrv.addHeaderView(View.inflate(this, R.layout.read_history_header, null));
        mPtrrv.setEmptyView(View.inflate(this, R.layout.read_history_empty_view, null));
        mPtrrv.removeHeader();
        mPtrrv.setLoadMoreFooter(loadMoreView);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_CODE_REFRESH) {
                if (arr.size() < 10) {
                    mAdapter.setCount(arr.size());
                } else {
                    mAdapter.setCount(DEFAULT_ITEM_SIZE);
                }
                mPtrrv.setOnRefreshComplete();
                mPtrrv.onFinishLoading(true, false);
            } else if (msg.what == MSG_CODE_LOADMORE) {
                if (arr.size() - mAdapter.getItemCount() >= 5) {
                    // Log.e("mAdapter", mAdapter.getItemCount()+ITEM_SIZE_OFFSET+"");
                    mAdapter.setCount(mAdapter.getItemCount() + ITEM_SIZE_OFFSET);
                    mPtrrv.onFinishLoading(true, false);
                } else if (arr.size() - mAdapter.getItemCount() < 5 && arr.size() - mAdapter.getItemCount() > 0) {
                    mAdapter.setCount(mAdapter.getItemCount() + arr.size() - mAdapter.getItemCount());
                    Log.e("mAdapter", mAdapter.getItemCount() + arr.size() - mAdapter.getItemCount() + "");
                    mPtrrv.onFinishLoading(true, false);
                } else if (arr.size() - mAdapter.getItemCount() < 0) {
                    mAdapter.setCount(mAdapter.getItemCount());
                } else {
                    //Log.e("mAdapter", "没有更多加载"+"");
                    //加载完毕
                    Toast.makeText(ReadHistoryActivity.this, "没有更多加载", Toast.LENGTH_SHORT).show();
                    mPtrrv.onFinishLoading(false, false);
                }
            }
        }
    };


    private void initData() {
        mDatas = new ArrayList<>();
        RequestParams params =
                new RequestParams("http://tr.zzapi.gson.cn//api/user/read/history");
        String uid = getIntent().getStringExtra("uid");

        params.addQueryStringParameter("page", "1");
        params.addQueryStringParameter("rows", "30");
        params.addQueryStringParameter("uid", uid);
        x.http().get(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                //Log.e("s/**-*-", s);
                JSONObject obj = JSON.parseObject(s);
                Boolean success = obj.getBoolean("success");
                if (success) {
                    arr = obj.getJSONArray("data");
                    Log.e("arr----------", arr.size() + "");
                    for (int i = 0; i < arr.size(); i++) {
                        Map<String, String> map = new HashMap<>();
                        map.put("title", arr.getJSONObject(i).getString("title"));
                        map.put("id", arr.getJSONObject(i).getString("id"));
                        map.put("views", arr.getJSONObject(i).getString("views"));
                        map.put("dateline", arr.getJSONObject(i).getString("dateline"));
                        mDatas.add(map);
                    }

                    mAdapter = new MyReadHistoryAdapter(ReadHistoryActivity.this, mDatas);
                    if (arr.size() < 10) {
                        mAdapter.setCount(arr.size());
                    } else {
                        mAdapter.setCount(DEFAULT_ITEM_SIZE);
                    }
                    mPtrrv.setAdapter(mAdapter);
                    mPtrrv.onFinishLoading(true, false);
                    mAdapter.setOnItemClickListener(new MyReadHistoryAdapter.OnItemClickListener() {
                        @Override
                        public void OnItemClick(View view, int position) {

                        }

                        @Override
                        public void OnItemLongClick(View view, final int position) {
                            final AlertDialog.Builder builder = new AlertDialog.Builder(ReadHistoryActivity.this);
                            View root = getLayoutInflater().inflate(R.layout.show_alertdialog_delete, null);
                            builder.setView(root);
                            final AlertDialog dialog = builder.create();
                            LinearLayout ll;
                            ll = (LinearLayout) root.findViewById(R.id.tv_show_dialog_delete);
                            ll.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mAdapter.removeRecycle(position);
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                throwable.printStackTrace();
            }
        });
    }
}

